import json
import os
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

class MyPaginator():
    def __init__(self, request, products):
        self.request = request
        self.products = products
        self.paginator = PageNumberPagination()

    def get_data(self):
        page = int(self.request.GET.get("page", 1))
        page_size = int(self.request.GET.get("page_size", 10))
        self.paginator.page = page
        self.paginator.page_size = page_size
        paginated_qs = self.paginator.paginate_queryset(self.products, self.request)
        return paginated_qs
    
    def get_page_info(self):
        page = self.paginator.page
        page_size = self.paginator.page_size
        count = self.paginator.page.paginator.count
        total = (count + page_size - 1) // page_size
        return {"page":page.number, "total":total,"page_size":page_size, "count":count,"has_pre":page.has_previous(),"has_next":page.has_next()}

class ResHelper():
    @staticmethod
    def success(data, status, **kwargs):
        return Response({"data": data, **kwargs}, status=status)
    
    @staticmethod
    def error(data, status, **kwargs):
        return Response({"data": data, **kwargs}, status=status)

class FakeRedis():
    def __init__(self, filepath="fake_redis.json"):
        self.filepath = filepath
        # 加载 json 文件，如果不存在就初始化空字典
        if os.path.exists(self.filepath):
            with open(self.filepath, "r", encoding="utf-8") as f:
                self.data = json.load(f)
        else:
            self.data = {}

    def _save(self):
        with open(self.filepath, "w", encoding="utf-8") as f:
            json.dump(self.data, f, ensure_ascii=False, indent=4)

    def set(self, key, value):
        self.data[key] = value
        self._save()

    def get(self, key):
        return self.data.get(key, None)
    
    def keys(self):
        return list(self.data.keys())

    def delete(self, key):
        if key in self.data:
            del self.data[key]
            self._save()  # 删除后保存数据
    
    